package org.wpahs.ahn.rssfeed;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;

import org.wpahs.ahn.rssfeed.DB.DBMyFeed;

import java.net.MalformedURLException;
import java.net.URL;



public class SyncSettingsFragment extends Fragment {
    Switch mSwhEnableAuto = null;
    private SeekBar mSeekAutoInMinutes = null;
    private TextView mSeedAutoInMinutesDisplay = null;
    private SharedPreferences mSharedPref = null;


    private OnFragmentInteractionListener mListener;

    public static SyncSettingsFragment newInstance() {
        SyncSettingsFragment fragment = new SyncSettingsFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public SyncSettingsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_syncsettings, container, false);
        setupUI(v);
        return v;
    }

    private void setupUI(View v){
        mSeekAutoInMinutes = (SeekBar)v.findViewById(R.id.settings_polltime);
        mSwhEnableAuto = (Switch)v.findViewById(R.id.settings_enableAuto);
        mSeedAutoInMinutesDisplay = (TextView)v.findViewById(R.id.settings_polltime_display);

        mSwhEnableAuto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mSeekAutoInMinutes.setEnabled(true);
                } else {
                    mSeekAutoInMinutes.setEnabled(false);
                }
                setAutoPoll(isChecked);
                if(isChecked) {
                    setSeekDisplay(getAutoInMinutes());
                }else{
                    setSeekDisplay(0);
                }

            }
        });

        boolean autoPoll = getAutoPoll();
        mSwhEnableAuto.setChecked(autoPoll);



        mSeekAutoInMinutes.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                setSeekDisplay(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(seekBar.getProgress() ==0){
                    seekBar.setProgress(1);
                }
                setAutoInMinutes(seekBar.getProgress());

            }
        });
        mSeekAutoInMinutes.setProgress(getAutoInMinutes());
        mSeekAutoInMinutes.setEnabled(autoPoll);

        if(autoPoll) {
            setSeekDisplay(getAutoInMinutes());
        }else{
            setSeekDisplay(0);
        }

        mSharedPref = getActivity().getSharedPreferences(
                getString(R.string.preferences_gambonereader), Context.MODE_PRIVATE);

    }

    private void setSeekDisplay(int progress){
        int minutes = progress % 60;
        if(progress > 0 && progress < 60) {
            mSeedAutoInMinutesDisplay.setText("Poll every " + progress + " minutes");
        }else if(progress >= 60){
            int hours = progress / 60;
            if(minutes == 0){
                mSeedAutoInMinutesDisplay.setText("Poll every " + hours + " hours");

            }else{
                mSeedAutoInMinutesDisplay.setText("Poll " + hours + " hours and " + minutes + " minutes");
            }
        }else{
            mSeedAutoInMinutesDisplay.setText("Manually refresh the feeds.");
        }
    }

    private void setAutoPoll(boolean isEnabled){
        if(mSharedPref == null){
            mSharedPref= getActivity().getSharedPreferences(
                    getString(R.string.preferences_gambonereader), Context.MODE_PRIVATE);
        }
        SharedPreferences.Editor editor = mSharedPref.edit();
        editor.putBoolean(getActivity().getString(R.string.preferences_enableAuto),
                isEnabled
        );
        editor.commit();

        if(isEnabled){
            RSSCastReceiver.SetupPolling(this.getActivity(),getAutoInMinutes());
        }else{
            RSSCastReceiver.ClearPolling(this.getActivity());
        }
    }

    private boolean getAutoPoll(){
        if(mSharedPref == null){
            mSharedPref= getActivity().getSharedPreferences(
                    getString(R.string.preferences_gambonereader), Context.MODE_PRIVATE);
        }
        return  mSharedPref.getBoolean(
                getActivity().getString(R.string.preferences_enableAuto),
                false);
    }

    private void setAutoInMinutes(int minutes){
        if(mSharedPref == null){
            mSharedPref= getActivity().getSharedPreferences(
                    getString(R.string.preferences_gambonereader), Context.MODE_PRIVATE);
        }
        SharedPreferences.Editor editor = mSharedPref.edit();
        editor.putInt(getActivity().getString(R.string.preference_autoPollInMinutes),
                minutes
        );
        editor.commit();
    }

    private int getAutoInMinutes(){
        if(mSharedPref == null){
            mSharedPref= getActivity().getSharedPreferences(
                    getString(R.string.preferences_gambonereader), Context.MODE_PRIVATE);
        }
        return  mSharedPref.getInt(
                getActivity().getString(R.string.preference_autoPollInMinutes),
                60
        );
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }



}
